package com.example.jobtask.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 热插拔任务上下文服务
 * 为热插拔任务提供Spring容器中的Bean和数据库连接
 */
@Service
public class HotPlugContextService {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    @Autowired
    private DataSource dataSource;
    
    // 静态实例，供热插拔任务使用
    private static HotPlugContextService instance;
    
    public HotPlugContextService() {
        instance = this;
    }
    
    /**
     * 获取静态实例
     */
    public static HotPlugContextService getInstance() {
        return instance;
    }
    
    /**
     * 获取Spring Bean
     */
    public <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
    
    /**
     * 获取Spring Bean by name
     */
    public Object getBean(String name) {
        return applicationContext.getBean(name);
    }
    
    /**
     * 获取数据库连接
     */
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    
    /**
     * 执行查询SQL
     */
    public Map<String, Object> queryForMap(String sql, Object... params) {
        Map<String, Object> result = new HashMap<>();
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    int columnCount = rs.getMetaData().getColumnCount();
                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = rs.getMetaData().getColumnName(i);
                        Object value = rs.getObject(i);
                        result.put(columnName, value);
                    }
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("执行查询失败: " + sql, e);
        }
        return result;
    }
    
    /**
     * 执行更新SQL
     */
    public int executeUpdate(String sql, Object... params) {
        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            
            // 设置参数
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }
            
            return ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("执行更新失败: " + sql, e);
        }
    }
}